package com.youlu.campus.starter.trace.config;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.rolling.RollingFileAppender;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Iterator;

@Slf4j
@Component
public class LogFilePathLogger {

    /**
     * 在应用启动完成后打印日志文件路径
     */
    @EventListener(ApplicationReadyEvent.class)
    public void logFilePathAfterStartup() {
        // 获取Logback的LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        // 遍历所有Appender查找文件输出的Appender
        for (ch.qos.logback.classic.Logger logger : loggerContext.getLoggerList()) {
            Iterator<Appender<ILoggingEvent>> appenderIterator = logger.iteratorForAppenders();
            while (appenderIterator.hasNext()) {
                Appender<ILoggingEvent> appender = appenderIterator.next();
                // 处理RollingFileAppender类型的日志输出
                if (appender instanceof RollingFileAppender) {
                    RollingFileAppender<?> fileAppender = (RollingFileAppender<?>) appender;
                    String filePath = fileAppender.getFile();
                    if (filePath != null) {
                        // 打印日志文件路径
                        LoggerFactory.getLogger(LogFilePathLogger.class).info("日志文件路径: {}", filePath);
                    }
                }
            }
        }
    }
}
    